using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.DataAccess.Common;
using T.FAS.Runtime.Metadata.Entity.DataModel;
using T.FAS.Runtime.Metadata.Entity;
using T.FAS.Runtime.Metadata.Client;
using T.FAS.Runtime.Metadata.SPI;

namespace T.FAS.Runtime.DataAccess.Engine
{
    public class RTPMetadataHelper
    {
        private static IMetaDataClientService metaDataClientService = MetaDataClientService.GetInstance();

        /// <summary>
        /// 运行时获取元数据
        /// </summary>
        /// <param name="metadataID"></param>
        /// <returns></returns>
        public static IMetaDataContent GetRTPMetadata(string metadataID)
        {
            if (EnvironmentSetting.RunningMode == RunningMode.LocalDebug)
            {
                return MockService.GetMetaData(metadataID);
            }
            else
            {
                return metaDataClientService.GetMetaData(metadataID).Content;
            }

            //if (DebugSetting.IsDebug)
            //    return MockService.GetMetaData(metadataID);
            //else
            //    return metaDataClientService.GetMetaData(metadataID).Content;
        }

        /// <summary>
        /// 运行时获取CDO的状态机
        /// </summary>
        /// <param name="cdo"></param>
        /// <param name="ColKey"></param>
        /// <returns></returns>
        public static List<StateMachineMetadata> GetSMMetaData(CompositeDataObject cdo, string ColKey = null)
        {
            List<StateMachineMetadata> result = new List<StateMachineMetadata>();
            var machines = cdo.RootCompositeNodeObject?.Elements.Where(e => e.StateMachines != null).SelectMany(e => e.StateMachines);
            if (string.IsNullOrEmpty(ColKey))
                machines = machines?.Where(m => m.CDOColKey == ColKey);
            var list = machines?.Where(m => m != null).ToList();
            try
            {
                if (list != null && list.Count > 0)
                {
                    foreach (var machine in list)
                    {
                        //调统一缓存服务运行时获取StateMachine 完整元数据
                        var realMachine = GetRTPMetadata(machine.ID) as StateMachineMetadata;
                        result.Add(realMachine);
                    }
                }
                return result;
            }
            catch (Exception e)
            {
                throw new FasException(DataAccessErrorCode.Metadata.Error, string.Format(CommonStringClassEngine.RTPMetadataHelper_GetSMMetaData,cdo.Code), e);
            }
        }
    }
}
